package com.byd.base;

import android.app.AlertDialog;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import com.byd.utils.Lg;

public abstract class BaseAlertDailog<T extends BaseDialogAction> extends AlertDialog {
	protected Resources mRes;
	private View mView;
	private int mAnimId = -1;
	private final Handler mHandler = new Handler(Looper.getMainLooper());
	private final T mAction;

	private String getTagStr() {
		return Lg.BASE_TAG + getClass().getSimpleName();
	}

	protected void v(Object msg) {
		Lg.v(getTagStr(), msg);
	}

	protected void d(Object msg) {
		Lg.d(getTagStr(), msg);
	}

	protected void i(Object msg) {
		Lg.i(getTagStr(), msg);
	}

	protected void w(Object msg) {
		Lg.w(getTagStr(), msg);
	}

	protected void e(Object msg) {
		Lg.e(getTagStr(), msg);
	}

	protected void wtf(Object msg) {
		Lg.wtf(getTagStr(), msg);
	}

	public BaseAlertDailog(Context context, T action) {
		super(context);
		v("new instance");
		mRes = context.getResources();
		getWindow().addFlags(
				WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
						| WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
		setView(mView = LayoutInflater.from(context).inflate(onInflateView(), null));
		if(mAnimId > 0) {
			getWindow().setWindowAnimations(mAnimId);
		}
		mAction = action;
		mView.postOnAnimation(mResize);
	}

	/** 返回布局文件ID */
	protected abstract int onInflateView();

	/** 有时对话框的宽度不能根据布局设置宽度 */
	protected int onMeasureWidth() {
		return 0;
	}

	protected int onMeasureMaxWidth() {
		return 0;
	}

	protected int onMeasureMinWidth() {
		return 0;
	}

	/** 有时对话框的高度不能根据布局设置高度 */
	protected int onMeasureHeight() {
		return 0;
	}

	protected int onMeasureMaxHeight() {
		return 0;
	}

	protected int onMeasureMinHeight() {
		return 0;
	}

	/** 如果对话框的宽度是根据屏幕来适配的，此返回屏幕的比例 */
	protected float onMeasureWidthPercent() {
		return 0;
	}

	protected float onMeasureMaxWidthPercent() {
		return 0;
	}

	protected float onMeasureMinWidthPercent() {
		return 0;
	}

	/** 如果对话框的高度是根据屏幕来适配的，此返回屏幕的比例 */
	protected float onMeasureHeightPercent() {
		return 0;
	}

	protected float onMeasureMaxHeightPercent() {
		return 0;
	}

	protected float onMeasureMinHeightPercent() {
		return 0;
	}

	private void transparent(View child) {
		final ViewParent parent = child.getParent();
		if(parent != null && parent instanceof ViewGroup) {
			final ViewGroup group = (ViewGroup) parent;
			group.setBackground(new ColorDrawable(Color.TRANSPARENT));
			transparent(group);
		}
	}

	@Override
	public void onStart() {
		super.onStart();
		transparent(mView);
	}

	private final Runnable mResize = new Runnable() {
		@Override
		public void run() {
			resize();
		}
	};

	private void resize() {
		final DisplayMetrics metrics = getDisplayMetrics();
		int w = onMeasureWidth();
		if(w <= 0) {
			w = (int) (metrics.widthPixels * onMeasureWidthPercent());
		}
		int h = onMeasureHeight();
		if(h <= 0) {
			h = (int) (metrics.heightPixels * onMeasureHeightPercent());
		}
		int maxW = onMeasureMaxWidth();
		if(maxW <= 0) {
			maxW = (int) (metrics.widthPixels * onMeasureMaxWidthPercent());
		}
		int maxH = onMeasureMaxHeight();
		if(maxH <= 0) {
			maxH = (int) (metrics.heightPixels * onMeasureMaxHeightPercent());
		}
		int minW = onMeasureMinWidth();
		if(minW <= 0) {
			minW = (int) (metrics.widthPixels * onMeasureMinWidthPercent());
		}
		int minH = onMeasureMinHeight();
		if(minH <= 0) {
			minH = (int) (metrics.heightPixels * onMeasureMinHeightPercent());
		}
		final View view = getWindow().getDecorView();
		final int currentW = view.getWidth();
		final int currentH = view.getHeight();
		int finalW, finalH;
		if(w > 0) {
			finalW = w;
		}
		else if(maxW > 0 && currentW > maxW) {
			finalW = maxW;
		}
		else if(minW > 0 && currentW < minW) {
			finalW = minW;
		}
		else {
			finalW = currentW;
		}
		if(h > 0) {
			finalH = h;
		}
		else if(maxH > 0 && currentH > maxH) {
			finalH = maxH;
		}
		else if(minH > 0 && currentH < minH) {
			finalH = minH;
		}
		else {
			finalH = currentH;
		}
		i("size: [" + finalW + ", " + finalH + "]");
		getWindow().setLayout(finalW, finalH);
	}

	public T getAction() {
		return mAction;
	}

	/** 延迟一段时间后自动隐藏Dialog */
	public void delayDismiss(int delayMillis) {
		postSingleDelayed(mHide, delayMillis);
	}

	/** 取消之前设置的延迟自动隐藏Dialog */
	public void cancelDelayDismiss() {
		removeCallbacks(mHide);
	}

	/** 设置Dialog背景颜色 */
	protected void setBackgroundColor(int color) {
		getWindow().setBackgroundDrawable(new ColorDrawable(color));
	}

	/** 设置Dialog背景 */
	protected void setBackground(Drawable drawable) {
		getWindow().setBackgroundDrawable(drawable);
	}

	/** 设置Dialog背景 */
	protected void setBackgroundResource(int resid) {
		getWindow().setBackgroundDrawableResource(resid);
	}

	/** 设置Dialog显示时，下层界面是否需要变暗 */
	protected void setBackgroundDark(boolean dark) {
		final LayoutParams params = getWindow().getAttributes();
		if(dark) {
			getWindow().addFlags(LayoutParams.FLAG_DIM_BEHIND);
		}
		else {
			getWindow().clearFlags(LayoutParams.FLAG_DIM_BEHIND);
		}
		params.dimAmount = dark ? 1f : 0;
		getWindow().setAttributes(params);
	}

	/** 设置Dialog显示和退出时的动画效果 */
	public void setWindowAnimations(int resId) {
		mAnimId = resId;
		if(getWindow() != null) {
			getWindow().setWindowAnimations(mAnimId);
		}
	}

	@Override
	public View findViewById(int id) {
		return mView.findViewById(id);
	}

	public final int getColor(int id) {
		return mRes.getColor(id);
	}

	public boolean getBoolean(int id) {
		return mRes.getBoolean(id);
	}

	public final float getDimension(int id) {
		return mRes.getDimension(id);
	}

	public final int getDimensionPixelOffset(int id) {
		return mRes.getDimensionPixelOffset(id);
	}

	public final int getDimensionPixelSize(int id) {
		return mRes.getDimensionPixelSize(id);
	}

	public final Drawable getDrawable(int id) {
		return mRes.getDrawable(id);
	}

	public final String getString(int id) {
		return mRes.getString(id);
	}

	public final String getString(int id, Object... formatArgs) {
		return mRes.getString(id, formatArgs);
	}

	public final String[] getStringArray(int id) {
		return mRes.getStringArray(id);
	}

	public final int getInteger(int id) {
		return mRes.getInteger(id);
	}

	public final int[] getIntArray(int id) {
		return mRes.getIntArray(id);
	}

	public final DisplayMetrics getDisplayMetrics() {
		return mRes.getDisplayMetrics();
	}

	public final Configuration getConfiguration() {
		return mRes.getConfiguration();
	}

	private final Runnable mHide = new Runnable() {
		@Override
		public void run() {
			dismiss();
		}
	};

	public final boolean post(Runnable r) {
		return mHandler.post(r);
	}

	public final boolean postSingle(Runnable r) {
		mHandler.removeCallbacks(r);
		return mHandler.post(r);
	}

	public final boolean postDelayed(Runnable r, long delayMillis) {
		return mHandler.postDelayed(r, delayMillis);
	}

	public final boolean postSingleDelayed(Runnable r, long delayMillis) {
		mHandler.removeCallbacks(r);
		return mHandler.postDelayed(r, delayMillis);
	}

	public final void removeCallbacks(Runnable r) {
		mHandler.removeCallbacks(r);
	}

	@Override
	protected void finalize() throws Throwable {
		i("finalize: " + toString());
		super.finalize();
	}
}
